package cn.zwx.learn.emqx.example.runner;

import cn.zwx.learn.emqx.example.config.MqttProperties;
import cn.zwx.learn.emqx.example.mqtt.MqttAcceptClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zhangwenxue
 * <code>
 *     mqtt 启动订阅来自其他客户端的消息
 * </code>
 */
@Component
public class EmqxServerRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(EmqxServerRunner.class);

    @Resource
    MqttAcceptClient mqttAcceptClient;
    @Resource
    MqttProperties mqttProperties;

    @Override
    public void run(String... args) {
        List<MqttProperties.SubscribeProperties> subscribes = mqttProperties.getSubscribes();
        if (CollectionUtils.isEmpty(subscribes)){
            logger.warn("mqtt subscribes is empty");
            return;
        }
        for (MqttProperties.SubscribeProperties subscribeMap : subscribes) {
                try {
                    mqttAcceptClient.subscribe(subscribeMap.getTopic(),subscribeMap.getOps());
                }catch (Exception e){
                    logger.error("mqtt subscribes topic:{} failed",subscribeMap.getTopic(),e);
                }
        }
    }
}
